// pages/add/travelbuy/travelbuy.js
Page({
  data: {
    isEdit: false,
    id: "",
    bottomHeight: getApp().globalData.bottomHeight,
    fileList: [],
    imgIds: [],
    content: "",
    label: "",
    end_date: "",
    end_time: "",
    isDate: false,
    isTime: false,
    currentDate: new Date().getTime(),
    currentDateString: "",
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      return value;
    },
    currentTime: "",
    addLabelShow: false,
    newLabel: "",
    selLabelIds: [],
    isSync: true,
    labelTip: true,
    btn_status: true
  },
  onLoad: function (options) {
    this.getLabels();
    if (options.edit == 1) {
      this.setData({
        isEdit: true,
        id: options.id
      });
      this.getDetail();
    }
  },
  getDetail() {
    getApp().globalData.http.detail({
      id: this.data.id
    }).then(res => {
      let tmp = res.data;
      let imgs = [];
      tmp.imgUrls = tmp.imgUrls.split(",");
      tmp.imgUrls.forEach(item => {
        imgs.push({
          url: item
        });
      });
      this.setData({
        fileList: imgs,
        imgIds: tmp.imgIds.split(","),
        title: tmp.title,
        content: tmp.content,
        price: tmp.price,
        stock: tmp.stock,
        currentDate: tmp.endTime,
        currentDateString: getApp().globalData.util.formatTime(new Date(tmp.endTime)).split(" ")[0],
        currentTime: getApp().globalData.util.formatTime(new Date(tmp.endTime)).split(" ")[1].slice(0, 5),
        selLabelIds: !tmp.labelIds ? [] : tmp.labelIds.split(","),
        isSync: tmp.isSync == 1 ? true : false
      });
    });
  },
  upload(e) {
    getApp().globalData.util.imgsUpload(this, e, this.data.fileList, this.data.imgIds);
  },
  delete(e) {
    let i = e.detail.index;
    let fileList = this.data.fileList;
    let imgIds = this.data.imgIds;
    fileList.splice(i, 1);
    imgIds.splice(i, 1);
    this.setData({
      fileList: fileList,
      imgIds: imgIds
    });
  },
  openDate() {
    this.setData({
      isDate: true,
    });
  },
  openTime() {
    this.setData({
      isTime: true,
    });
  },
  dateConfirm(event) {
    this.setData({
      currentDate: event.detail,
      currentDateString: getApp().globalData.util.formatTime(new Date(event.detail)).split(" ")[0],
      isDate: false
    });
  },
  timeConfirm(event) {
    this.setData({
      currentTime: event.detail,
      isTime: false
    });
  },
  dateCancel() {
    this.setData({
      isDate: false,
    });
  },
  timeCancel() {
    this.setData({
      isTime: false,
    });
  },
  addLabel() {
    this.setData({
      addLabelShow: true
    });
  },
  getLabels() {
    getApp().globalData.http.getUserAddLabel({
      type: 6
    }).then(res => {
      this.setData({
        userAddLabels: res.data
      });
    });
  },
  addLabelConfirm() {
    if (this.data.newLabel.length > 5) {
      this.setData({
        labelTip: false
      });
    } else {
      this.setData({
        labelTip: true
      });
      getApp().globalData.http.saveUserAddLabel({
        name: this.data.newLabel,
        type: 6
      }).then(res => {
        getApp().globalData.vant.toast("添加成功");
        this.getLabels();
        this.setData({
          newLabel: ""
        });
      });
    }
  },
  selLabel(e) {
    let id = e.currentTarget.dataset.id;
    let arr = this.data.selLabelIds;
    if (!arr.includes(id)) {
      if (arr.length < 3) arr.push(id);
    } else {
      arr.splice(arr.indexOf(id), 1);
    }
    this.setData({
      selLabelIds: arr
    });
  },
  labelDel(e) {
    getApp().globalData.vant.dialog.confirm({
        title: "提示",
        message: "确认要删除么？",
        zIndex: 3000,
        confirmButtonColor: "#33B868"
      })
      .then(() => {
        getApp().globalData.http.delUserAddLabel({
          id: e.currentTarget.dataset.id
        }).then(res => {
          getApp().globalData.vant.toast("删除成功");
          this.getLabels();
          this.setData({
            addLabelShow: false
          });
        });
      })
      .catch(() => {});
  },
  syncHandle() {
    this.setData({
      isSync: !this.data.isSync
    });
  },
  submit() {
    let params = {
      type: 6,
      content: this.data.content,
      imgIds: this.data.imgIds.join(","),
      end_date: this.data.currentDateString,
      end_time: this.data.currentTime,
      labelIds: this.data.selLabelIds.join(","),
      isSync: this.data.isSync ? 1 : 0,
    };
    if (this.data.btn_status) {
      if (!params.imgIds) {
        getApp().globalData.vant.toast("您还没有上传图片");
      } else if (!params.content) {
        getApp().globalData.vant.toast("商品介绍不能为空");
      } else if (!params.end_date) {
        getApp().globalData.vant.toast("请选择截止日期");
      } else if (!params.end_time) {
        getApp().globalData.vant.toast("请选择截止时间");
      } else if (new Date().getTime() > new Date(`${this.data.currentDateString} ${this.data.currentTime}:00`).getTime()) {
        getApp().globalData.vant.toast("截止时间必须大于当前时间");
      } else {
        this.setData({
          btn_status: false
        });
        params.endTimeStr = params.end_date + " " + params.end_time;
        if (!this.data.isEdit) {
          getApp().globalData.http.squarePost(params).then(res => {
            getApp().globalData.vant.toast({
              type: "success",
              forbidClick: true,
              message: "发布成功",
              onClose: () => {
                wx.switchTab({
                  url: "/pages/home/home",
                  success: function (e) {
                    var page = getCurrentPages().pop();
                    if (page == undefined || page == null) return;
                    page.reset();
                  }
                });
              }
            });
          }).catch(e => {
            this.setData({
              btn_status: true
            });
          });
        } else {
          params.id = this.data.id
          getApp().globalData.http.squareUpdate(params).then(res => {
            getApp().globalData.vant.toast({
              type: "success",
              forbidClick: true,
              message: "保存成功",
              onClose: () => {
                wx.navigateBack({
                  success: function (e) {
                    var page = getCurrentPages().pop();
                    if (page == undefined || page == null) return;
                    page.reset();
                  }
                });
              }
            });
          }).catch(e => {
            this.setData({
              btn_status: true
            });
          });
        }
      }
    }
  }
})